import type { ITreeWithChild } from './index.d'

// 传参编码
export function encodeQuery(query: { [key: string]: any }): string {
  let queryStr = ''
  let keys = Object.keys(query)
  keys.forEach((item, index) => {
    queryStr = index
      ? `${queryStr}&${item}=${query[item]}`
      : `${queryStr}${item}=${query[item]}`
  })
  return queryStr
}

// 接收解码
export function decodeQuery(queryStr: string): any {
  let query: { [key: string]: any } = {}
  queryStr = decodeURI(queryStr.replace('?', ''))
  let queryArr = queryStr.split('&')
  queryArr.forEach(item => {
    let keyAndValue = item.split('=')
    query[keyAndValue[0]] = keyAndValue[1]
  })
  return query
}

// 深克隆
export function deepClone(source: any): any {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments, deepClone')
  }
  const targetObj: any = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

// 把树拍平为一维数组
export function union<T>(arr: ITreeWithChild<T>[], resArr: ITreeWithChild<T>[] = []) {
  arr.forEach(item => {
    const node = { ...item };

    if (node.children && node.children.length) {
      union(node.children, resArr)
      delete node.children
    };

    resArr.push(node)
  })

  return resArr
}